package com.ys.context;

import com.ys.bean.factory.AbstractBeanFactory;
import com.ys.bean.support.BeanDefinitionRegistry;
import com.ys.exception.BeanDefinitionStoreException;
import com.ys.exception.BeansException;

/**
 * <p>@description:</p>
 *
 * @projectName: Spring-Mini
 * @packageName: com.com.ys.context
 * @className:
 * @author: shuangyang
 * @date: 1/15/17 9:23 PM
 */
public abstract class AbstractApplicationContext implements ApplicationContext {
    protected AbstractBeanFactory beanFactory;

    public AbstractApplicationContext(AbstractBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    public String getApplicationName() {
        return "";
    }

    public void refresh() {
        try {
            loadBeanDefinitions(beanFactory);
        } catch (BeanDefinitionStoreException e) {
            e.printStackTrace();
        }
        onRefresh();
    }


    /**
     * 加载beanDefinitions
     *
     * @param registry
     * @throws BeanDefinitionStoreException
     */
    protected abstract void loadBeanDefinitions(BeanDefinitionRegistry registry) throws BeanDefinitionStoreException;

    protected void onRefresh() {

    }

    /**
     * 通过beanName获取bean实例
     *
     * @param beanName
     * @return
     */
    @Override
    public <T> T getBeanByName(String beanName) throws BeansException {
        return beanFactory.getBeanByName(beanName);
    }

    /**
     * 根据class类型获取bean实例；
     *
     * @param requiredType
     * @return
     */
    @Override
    public <T> T getBeanByType(Class<T> requiredType) throws BeansException {
        return beanFactory.getBeanByType(requiredType);
    }
}
